package cn.bluemobi.app.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.bluemobi.app.entity.output.VerifyCode;
import cn.bluemobi.app.mapper.MemberMapper;
import cn.bluemobi.app.service.VerifyCodeService;
import cn.bluemobi.app.utils.CommonUtils;
import cn.bluemobi.app.utils.WebserviceUtils;
import cn.bluemobi.common.core.dto.Dto;

import com.aliyuncs.exceptions.ClientException;

/**
 * 
 * @author lvxh
 * 
 */
@Service
@Transactional
public class VerifyCodeServiceImpl implements VerifyCodeService {

	@Autowired
	private MemberMapper memberMapper;

	@Autowired
	private EhCacheCacheManager cacheManager;

	@Override
	public Dto<VerifyCode> getVerifyCode(String cellphone, String type)
			throws ClientException {
		Dto<VerifyCode> dto = new Dto<VerifyCode>();
		String verifyCodeCacheName = null;
		VerifyCode verifyCode = new VerifyCode();
		verifyCode.setVerifyCode(CommonUtils.createNumber(6));
		// verifyCode.setVerifyCode("666666");
		if (StringUtils.equals(type, "0")) {
			if (memberMapper.checkIsExistCellphone(cellphone) > 0) {
				dto.errorMsg("账号已存在,前去登录?");
				return dto;
			}
			verifyCodeCacheName = cellphone + "regVerifyCode";
		}
		if (StringUtils.equals(type, "1")) {
			if (memberMapper.checkIsExistCellphone(cellphone) <= 0) {
				dto.errorMsg("账号不存在,前去注册?");
				return dto;
			}
			verifyCodeCacheName = cellphone + "fpVerifyCode";
		}

		Map<String, String> params = new HashMap<String, String>();
		params.put("code", verifyCode.getVerifyCode());
		// SmsUtils.sendSms(cellphone, "{\"code\":\"" +
		// verifyCode.getVerifyCode()
		// + "\"}");
		Long result = WebserviceUtils.sendSms(cellphone, "尊敬的用户您好，您的短信验证码为："
				+ verifyCode.getVerifyCode() + "，请在五分钟内完成认证，感谢您的使用！【瑞迪购商城】");
		if (result > 0) {
			dto.setData(verifyCode);
			cacheManager.getCache("verifyCodeCache").put(verifyCodeCacheName,
					verifyCode.getVerifyCode());
		} else {
			dto.errorMsg("短信发送失败");
		}
		return dto;
	}
}
